from ..exception.TestException import TestException
from ..common.ui.PageElement import PageElement
from ..exception.errorcode import ErrorCode


class Combotree(PageElement):
    """
    Fish Combotree Component
    https://fish.iwhalecloud.com/fish-desktop/api/index.html#!/api/fish.desktop.widget.Combotree
    """

    def get_data_value_field(self):
        """
        获取初始化设置dataValueField
        :return:
        """
        script = "return $(arguments[0]).combotree('option', 'dataValueField')"
        return self._driver.execute_script(script, self._get_web_element())

    def get_data_text_field(self):
        """
        获取初始化设置dataValueField
        :return:
        """
        default_text_field = 'name'
        script = "return $(arguments[0]).combotree('option', 'data.key.name')"
        text_field = self._driver.execute_script(script, self._get_web_element())
        return text_field if text_field is not None else default_text_field

    def get_datasource(self):
        """
        获取初始化设置dataValueField
        :return:
        """
        script = "var node = $(arguments[0]).combotree('getTreeInstance').tree('getNodes');" \
                 "return $(arguments[0]).combotree('getTreeInstance').tree('transformToArray',node)"
        datasource = self._driver.execute_script(script, self._get_web_element())
        if datasource is None:
            raise TestException.by_error_code(ErrorCode.COMBOTREE_NOT_DATA_SOURCE)
        return datasource

    def getValue(self) -> dict:
        self.wait_element_presence()
        script = "return $(arguments[0]).combotree('value')"
        return self._driver.execute_script(script, self._get_web_element())

    def setValue(self, text):
        """
        设置选中Combotree值, 调用combotree.value
        :param text:
        :return:
        """
        self.wait_element_presence()
        value_field = self.get_data_value_field()
        text_field = self.get_data_text_field()
        datasource = self.get_datasource()
        value = None
        for data in datasource:
            if text == data[text_field]:
                value = data[value_field]
                break
        if value is None:
            raise TestException.by_error_code(ErrorCode.COMBOTREE_VALUE_NOT_EXIST, value=text)
        script = "$(arguments[0]).combotree('value','{value}')".format(value=value)
        self._execute_script(script, self._get_web_element(), value)

    def get_identification(self):
        identification = {'class': ['form-control'],
                          'data-ui-role': ['combotree']}
        return identification
